// 手机号校验
export const phoneRule = [
  {
    required: true,
    message: "请输入手机号",
    trigger: "change", // 触发校验的时机，这里设置为失焦时校验
  },
  {
    pattern: /^1[3456789]\d{9}$/,
    message: "请输入有效的手机号",
    trigger: "change",
  },
]

// 邮箱校验
export const emailRule = [
  {
    required: true,
    message: "请输入邮箱",
    trigger: "change", // 触发校验的时机，这里设置为失焦时校验
  },
  {
    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    message: "请输入有效的邮箱",
    trigger: "change",
  },
]

// 身份证校验
export const idcardRule = [
  {
    trigger: "change",
    validator: (_rule, id) => {
      var re = /^(\d{17})(\d|X)$/;
      var match = id.match(re);
      if (match) {
        // 获取最后一位数字或字母
        var lastChar = match[2];
        // 计算校验码
        var weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        for (var i = 0; i < 17; i++) {
          sum += parseInt(id[i]) * weight[i];
        }
        var checkCode = parity[sum % 11];
        if (checkCode === 'X') {
          checkCode = 'X'.charCodeAt(0);
        } else {
          checkCode = parseInt(checkCode);
        }
        // 比较校验码是否匹配
        if (parseInt(lastChar) === checkCode) {
          return Promise.resolve();
        } else {
          return Promise.reject('请输入有效的身份证');
        }
      } else {
        return Promise.reject('请输入有效的身份证');
      }
    }
  },
]